package com.atguigu.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.atguigu.springboot.componet.MyLocaleResolver;
import com.atguigu.springboot.service.HelloService;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyConfig implements WebMvcConfigurer {

    //添加视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //super.addViewControllers(registry);
        //表示:当访问路径为atguigu时,到success页面
        registry.addViewController("/atguigu").setViewName("success");
        registry.addViewController("/index").setViewName("index");
        
    }
	
	@Bean
	public WebMvcConfigurer webMvcConfigurerAdapter(){
		WebMvcConfigurer adapter = new WebMvcConfigurer() {
		    @Override
		    public void addViewControllers(ViewControllerRegistry registry) {
			    //但在这里配置了main路径转向了dashboard页面,如果直接访问main路径,那么index登陆页面就没用了
			    registry.addViewController("/main").setViewName("dashboard");
		    }
		    
		    @Override
		    public void addInterceptors(InterceptorRegistry registry) {
		    	//在这里注册拦截器,这里的意思是添加拦截器,拦截路径为/**的路径,但不拦截/index及/路径还有/user/login路径,
			    // 这几个路径用户登陆和访问登陆页面的
			    //而在springboot中不要配置排除静态资源的路径,springboot已经配置好了静态资源的路径,拦截器不会进行拦截
		    	//registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index","/","/user/login");
		    }
	    };
	    return adapter;
	}

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

    //添加

    @Bean
    public HelloService helloService(){
        return new HelloService();
    }
    
    //使用代码对server进行配置
	@Bean
	public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
    	return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
		    @Override
		    public void customize(ConfigurableWebServerFactory factory) {
				factory.setPort(8080);
		    }
	    };
	}
	
	//注册servlet
	@Bean
	public ServletRegistrationBean setServlet(){
    	return new ServletRegistrationBean(new HttpServlet() {
		    @Override
		    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			    doPost(req,resp);
		    }
		
		    @Override
		    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			    super.doPost(req, resp);
			    System.out.println("进入了servlet");
		    }
	    }, "/myservlet");
	}
	
	//注册filter
	@Bean
	public FilterRegistrationBean setFilter(){
		FilterRegistrationBean myfilter = new FilterRegistrationBean(new Filter() {
			@Override
			public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
				System.out.println("进过滤器了!");
				filterChain.doFilter(servletRequest, servletResponse);
			}
		});
		myfilter.addUrlPatterns("/myservlet");
		return myfilter;
	};
    
    //注册listener
    @Bean
	public ServletListenerRegistrationBean<ServletContextListener> setApplicationListener(){
    	return new ServletListenerRegistrationBean<>(new ServletContextListener() {
		    @Override
		    public void contextInitialized(ServletContextEvent sce) {
			    System.out.println("项目启动!!");
		    }
		
		    @Override
		    public void contextDestroyed(ServletContextEvent sce) {
			    System.out.println("项目停止!!");
		    }
	    });
    }
    
    //===================druid数据源配置===============================
	//首先配置druid数据源并绑定配置文件中的配置信息,
    //这里使用@ConfigurationProperties(prefix = "spring.datasource")将配置文件中spring.datasource的属性绑定到数据源中
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druid(){
    	//返回我们自己的数据源
    	return new DruidDataSource();
	}
	
	//配置druid数据源的监控
	/*
	 * 要配置druid数据源有两个步骤,这里注册的是druid提供的servlet和filter
	 * 1、配置一个管理后台的Servlet(druid的servlet是StatViewServlet)
	 * 2、配置一个web监控的filter(druid的filter是WebStatFilter)
	 */
	//配置管理后台的servlet,在springboot中将servlet封装了且没有web.xml来注册servlet,
	//我们可以用之前学习的springboot提供servlet的方式来注册,而需要注册的druid的servlet是StatViewServlet
	@Bean
	public ServletRegistrationBean statViewServlet(){
		ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
		Map<String, String> initParams = new HashMap<>();
		initParams.put("loginUsername","admin");//设置druid后台管理的登录名
		initParams.put("loginPassword","123456");//后台管理登录密码
		initParams.put("allow","");//允许XXX访问,为空串时默认就是允许所有访问
		//initParams.put("deny","192.168.1.102");//阻止XXX访问
		//设置druid数据源的一些配置
		bean.setInitParameters(initParams);
		return bean;
	}
	
	//配置web监控的filter,需要注册的druid的filter是WebStatFilter
	@Bean
	public FilterRegistrationBean statViewFilter(){
		FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
		Map<String,String> initParams = new HashMap<>();
		//不拦截哪些路径,静态文件和druid的路径不拦截
		initParams.put("exclusions","*.js,*.css,/druid/*");
		
		bean.setInitParameters(initParams);
		
		//配置拦截的路径,这里是拦截所有
		bean.setUrlPatterns(Arrays.asList("/*"));
		
		return  bean;
	}
	
	//配置Mybatis
	/*@Bean
	public ConfigurationCustomizer mybatisCustomizer(){
		return a -> a.setMapUnderscoreToCamelCase(true);
	}*/
}
